package com.tuling.jucdemo.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author :tangweiliang
 * @date : 2022/11/16 22:13
 * 未来的你会感谢现在努力的自己
 *
 * 同步执行
 */
public class ReentrantLockDemo {
    private static int sum = 0;
    //private static TulingLock lock = new TulingLock();
    private static Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            Thread thread = new Thread(()->{
                //加锁
                lock.lock();
                    try {
                        // 临界区代码
                        // TODO 业务逻辑：读写操作不能保证线程安全
                        for (int j = 0; j < 10000; j++) {
                            sum++;
                        }
                    }finally {
                        // 解锁
                        lock.unlock();
                    }
            });
            thread.start();
        }

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("sum="+sum);
    }
}
